XM.lang.namespace('XM.canvas');

XM.canvas.RenderController = {
    layersManager: XM.canvas.LayerManager,
    context: null,
    /**
     * 绘制一帧
     */
    paintStep: function () {
        this.context = GLOBAL_CONFIG['canvas'].getContext('2d');
        var layers = this.layersManager.layers; //console.log(layers.layers);
        for (var i = 0, len = layers.length; i < len; i++) {
            this._paintStep(layers[i].items);
        }
    },

    _paintStep: function (items) {
        for (var j = 0, len = items.length; j < len; j++) {
            var item = items[j];

            //if (item.isHide) continue;

            if (item instanceof Array) {
                this._paintStep(item);
            } else {
                if (item.width) {
                    //console.log(item.image, item.imageX, item.imageY, item.width, item.height,
                    //        item.x, item.y, item.width, item.height);
                    //try {
                        GLOBAL_CONFIG['canvas'].getContext('2d').drawImage(
                                item.image, item.imageX, item.imageY, item.imageWidth, item.imageHeight,
                                item.x, item.y, item.width, item.height);
                    //} catch (e) {
                        //console.log(e, item.row, item.column);
                    //}
                    //alert('b');
                } else {
                    GLOBAL_CONFIG['canvas'].getContext('2d').drawImage(item.image, item.x, item.y);
                }
            }

            if (item.items) this._paintStep(item.items);
        }
    },

    /**
     * 开始渲染
     */
    play: function () {
        setInterval(function () {
            //var sTime = new Date(), eTime = 0;
            for (var i = 0, len = XM.canvas.LayerManager.layers.length; i < len; i++) {
                XM.canvas.RenderController._paintStep(XM.canvas.LayerManager.layers[i].items);
            }
            //eTime = new Date();
            //console.log('paint frame: ' + (1 / ((eTime.getTime() - sTime.getTime()) / 1000)));
        }, GLOBAL_CONFIG['global'].paintMillisecond);
    }
};